import React, { createContext, useContext, useState, ReactNode } from 'react';

// 定义用户类型
interface User {
  id: number;
  name: string;
  email: string;
  role: 'user' | 'admin';
}

// 定义上下文类型
interface UserContextType {
  user: User | null;
  login: (user: User) => void;
  logout: () => void;
  updateUser: (updates: Partial<User>) => void;
  isLoggedIn: boolean;
}

// 创建Context
const UserContext = createContext<UserContextType | undefined>(undefined);

// 自定义Hook
export const useUser = () => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser必须在UserProvider中使用');
  }
  return context;
};

// Provider组件
interface UserProviderProps {
  children: ReactNode;
}

export const UserProvider: React.FC<UserProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);

  const login = (userData: User) => {
    setUser(userData);
  };

  const logout = () => {
    setUser(null);
  };

  const updateUser = (updates: Partial<User>) => {
    setUser(prevUser => prevUser ? { ...prevUser, ...updates } : null);
  };

  return (
    <UserContext.Provider value={{
      user,
      login,
      logout,
      updateUser,
      isLoggedIn: !!user
    }}>
      {children}
    </UserContext.Provider>
  );
};